#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/9/2 14:36
# @Author : wn 
# @File: tradeSearch.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡
import json

from django.shortcuts import render
from django.views import View

from Manager.utils.mypage import my_page
from Manager.utils.pageSearch import *
import datetime


class TradeSearch(View):
    def get(self, request):
        # 当前在第几页
        off = request.GET.get('offset', None)
        # 一页几条
        lim = request.GET.get('limit', None)
        if lim is None:
            html = "tradeSearch.html"
            return render(request, html, {'url': '/strategy/trade_list'})
        else:
            result_list = []
            nowtime = datetime.datetime.now().strftime('%Y%m%d')
            # 报单查询
            ta_list = list(Ruletrade.objects.filter(tradingday=nowtime))

            for item in ta_list:
                result_dict = {}
                result_dict['Tradingday'] = item.tradingday
                result_dict['RuleID'] = item.ruleid
                result_dict['AccountID'] = item.accountid
                result_dict['TradeID'] = item.tradeid
                result_dict['OrderSysID'] = item.ordersysid
                result_dict['OrderInnerID'] = item.orderinnerid
                result_dict['AssetNo'] = item.assetno
                result_dict['CombiNo'] = item.combino
                result_dict['InstrumentID'] = item.instrumentid
                result_dict['Direction'] = DirectionChoices.get(item.direction, None)
                result_dict['OffSetFlag'] = OffsetFlagChoices.get(item.offsetflag, None)
                result_dict['Price'] = item.tradeprice
                result_dict['VolumeTraded'] = item.volumetraded
                result_dict['TradeTime'] = item.tradetime
                result_list.append(result_dict)
            # 排序
            for item in result_list:
                if (item.get('tradingday') is None):
                    item['tradingday'] = '-1'
            result_list_sorted = sorted(result_list, key=itemgetter('tradingday'), reverse=True)
            result = my_page(result_list_sorted, lim, off)
            return JsonResponse(result, safe=False)

    def post(self, request):
        if request.POST.get('tradeSearch_select', None):
            data = json.loads(request.POST.get('data'))
            Tradingday = data.get('Tradingday', None)
            RuleID = data.get('RuleID', None)
            TradeID = data.get('TradeID', None)
            OrderSysID = data.get('OrderSysID', None)
            AccountID = data.get('AccountID', None)
            InstrumentID = data.get('InstrumentID', None)
            jsonRes = search_tradesearch(Tradingday=Tradingday, RuleID=RuleID, TradeID=TradeID,OrderSysID=OrderSysID, AccountID=AccountID, InstrumentID=InstrumentID)
            return jsonRes
